package main

import (
	"encoding/json"
	"fmt"
	"go-demo-2025/demo/common"
)

// 关于go中组合结构体赋值的问题
type User struct {
	Id               int64
	Name             string
	Age              int64
	UserInfo         //组合当前package的结构体
	common.ExtraData //组合其它package的结构体
}

// 定义二维结构体
type User2 struct {
	Id    int64            `json:"id"`
	Name  string           `json:"name"`
	Age   int64            `json:"age"`
	Info  UserInfo         `json:"info"` //注意:这里需要给组合的结构体前面加一个属性名称
	Extra common.ExtraData `json:"extra"`
}

type UserInfo struct {
	Phone   string
	Address string
}

func main() {
	//方式1
	var user1 User
	user1.Id = 1
	user1.Name = "张三"
	user1.Age = 18
	user1.Phone = "123456789"
	user1.Address = "北京"
	user1.ExtraId = 100
	user1.ExtraName = "extraName"
	jsonData1, _ := json.Marshal(user1)
	fmt.Println(string(jsonData1))

	//方式2
	user2 := User{
		Id:   1,
		Name: "张三",
		Age:  18,
		UserInfo: UserInfo{ //组合当前package的结构体
			Phone:   "123456789",
			Address: "北京",
		},
		ExtraData: common.ExtraData{ //组合其它package的结构体
			ExtraId:   100,
			ExtraName: "extraName",
		},
	}
	jsonData2, _ := json.Marshal(user2)
	fmt.Println(string(jsonData2))

	/*
		//方式2的错误写法1:
		user2Error1 := User{
			Id:   1,
			Name: "张三",
			Age:  18,
			UserInfo{ //报错:Mixture of fields: value and value initializers
				Phone:   "123456789",
				Address: "北京",
			},
			common.ExtraData{
				ExtraId:   100,
				ExtraName: "extraName",
			},
		}

		//方式2的错误写法2:
		user2Error1 := User{
			Id:        1,
			Name:      "张三",
			Age:       18,
			Phone:     "123456789", //报错:读取不到此属性 Unknown field 'Phone' in struct literal,下同
			Address:   "北京",
			ExtraId:   200,
			ExtraName: "hello",
		}
	*/

	//输出二维结构
	var u1 User2
	u1.Id = 2
	u1.Name = "李四"
	u1.Age = 25
	u1.Info.Phone = "131000001"
	u1.Info.Address = "上海"
	u1.Extra.ExtraId = 300
	u1.Extra.ExtraName = "extraName1"
	json1, _ := json.Marshal(u1)
	fmt.Println(string(json1))

	u2 := User2{
		Id:   3,
		Name: "王五",
		Age:  39,
		Info: UserInfo{
			Phone:   "1891234",
			Address: "深圳",
		},
		Extra: common.ExtraData{
			ExtraId:   400,
			ExtraName: "extraName2",
		},
	}
	json2, _ := json.Marshal(u2)
	fmt.Println(string(json2))
}
